﻿@model MasoQna.Models.Question

<div id="questionTitle">
    <h1>@Model.Title</h1>
</div>
<div>
    <article>
        @{ Html.RenderPartial("ReadPart", Model); }

        <div id="answerCount">
            <span>@(string.Format("{0}개의 답변", Model.Answers.Count))</span>
        </div>
        <div id="answerContainer">
            @if (Model.Answers.Count > 0)
            {
                 foreach (Answer a in Model.Answers)
                 {
                     Html.RenderPartial("ReadPart", a);
                 }
            }
        </div>
        <div id="readPageFooter">
            @if (Request.IsAuthenticated)
            {
                @Html.Partial("Editor")
                <div id="errMsg"></div>
                <input type="button" id="postAnswer" value="답변 올리기" class="submitBtn"/>
            }
            else
            {
                string linkStr = Html.ActionLink("로그인", "Index", "Account",
                    new { elReturnUrl = Url.Encode(Request.RawUrl) }, new { }).ToString();
                string pleaseLogin = string.Format("답을 알고 계신가요? {0}해서 도움을 주세요", linkStr);
                
                <div id="loginToAnswer">
                    @(new MvcHtmlString(pleaseLogin))
                </div>
            }
        </div>
        
    </article>
    <aside>
    </aside>
</div>

<script type="text/javascript">
function changeAnswerCount(increase) {
    var target = $('#answerCount span');
    var countText = target.text();
    var count = countText.match(/\d+/);
    count = parseInt(count);
    
    if (increase) count++;
    else count--;

    countText = countText.replace(/\d+/, "" + count);
    target.text(countText);
}

function onQuestionsReadLoad(isLoggedIn, noAnswer, isQuestionWriter) {
    if (isLoggedIn) {
        $(document).ready(function () {
            $('#postAnswer').click(function (event) {
                $.post(
                '/Questions/PostAnswer',
                {
                    questionId: @(Model.Id),
                    answerText: Editor.getContent()
                },
                function (response) {
                    if (response.Errors == null) {
                        $('#answerContainer').append(response);
                        $('#answerCount').show();
                        changeAnswerCount(true);
                    } else {
                        showErrors($('#errMsg'), response.Errors);
                    }
                }
            );
            });
        });
    }

    if (noAnswer) {
        $('#answerCount').hide();
    }
}
@{
    int userId = -1;
    if (Request.IsAuthenticated)
    {
        userId = Int32.Parse(User.Identity.Name); 
    }
}
onQuestionsReadLoad(@((Request.IsAuthenticated).ToString().ToLower()), @((Model.Answers.Count == 0).ToString().ToLower()), @((userId == Model.Writer.Id).ToString().ToLower()));
</script>